<?php
namespace app\mini\controller;
use think\Controller;
use think\Db;
// 星盘档案管理控制器
class Login extends Controller
{
    private $appid;
    private $appsecret;
    const ACCESS_TOKEN_URL = 'https://api.weixin.qq.com/sns/jscode2session';

    public function _initialize()
    {

        $this->appid = config('wechat.mini_appid');
        $this->appsecret = config('wechat.mini_appsecret');
    }
    public function index()
    {
        $code = htmlspecialchars(input('code'));

        $access_token_url = self::ACCESS_TOKEN_URL
            . "?appid=".$this->appid.'&secret='.$this->appsecret
            .'&js_code='.$code.'&grant_type=authorization_code';

        $wx_data = json_decode($this->curl_get($access_token_url),true);

        if(isset($wx_data['errcode'])) return json(['code'=>$wx_data['errcode'],'msg'=>$wx_data['errmsg']]);

        $hasRecode = 0;

        $app_user = Db::table('wechat_backup_07_18_14_43_00.app_wechat')
            ->alias('wu')
            ->field('u.has_self_recode')
            ->join('wechat_backup_07_18_14_43_00.app_user u','u.id=wu.uid','INNER')
            ->where("wu.unionid='{$wx_data['unionid']}'")
            ->find();

        if($app_user && $app_user['has_self_recode'] == 1) $hasRecode = 1;

        return json(['code'=>200,'data'=>[
            'openid'=>$wx_data['openid'],
            'unionid'=>$wx_data['unionid'],
            'has'=>$hasRecode
        ],'msg'=>'ok']);
//        array(4) {
//            ["session_key"] => string(24) "Ahif6j/WMansf59TqOvE4Q=="
//            ["expires_in"] => int(7200)
//            ["openid"] => string(28) "oOvcY0TCDAM7-q3wu64_WAUQ-3Bg"
//            ["unionid"] => string(28) "oIVMdt3ImvlYxHFjRcbUv1PON-c4"
//    }
    }



    /**
     * 发起GET请求
     * @param string $url
     * @return mixed
     */
    private function curl_get($url='')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

}